import {doubleValidate}  from '~/utils/validate'
import {fetchList,delObj,addObj,editObj,getObj} from '@/views/assess/api/assess-template.js'
export default {
    name: "assessTemplate",
		provide () {
			return {
				initList: this.getListData
			};
		},
    data(){
        return{
            tableData: [],//所有模板
            formData:{},//当前编辑的模板
            rules_formDataDetail:{
                formDataDetail:[],
                rules:{
                    item:[{ required: true, message: "请输入考核项目", trigger: "blur" }],
                    weightValue:[
                        {required: true,type: 'number', message: "请输入数字代表权重", trigger: "change"},
                        {validator:doubleValidate,trigger: "change"},
                        ]
                }
            },//模板明细
            rules:{
                name:[{ required: true, message: "请输入考核项目", trigger: "blur" }],
            },
            searchForm:{},
            dialogVisible:false,//新增弹出框
            isEdit:'',//是编辑还是保存
						// 请求参数
						params: {
							current: 1,
							size: 20,
							name: ""
						},
						// 分页
						pager: {
							total: 0, // 总页数
							current: 1, // 当前页数
							size: 20 // 每页显示多少条
						},
						// 页面loading
						loading: false,
        }
    },
		beforeMount () {
			this.getListData();
		},
    methods: {
        save(){
            if(this.valiTableData(this.rules_formDataDetail.formDataDetail)){
                this.$confirm('该列表数据中有相同的考核项，您是否需要修改？', '提示', {
                    confirmButtonText: '不需要',
                    cancelButtonText: '需要',
                    type: 'warning'
                }).then(() =>{
                    this.saveData()
                })
            }else{
                this.saveData()
            }


        },
        saveData(){
            if (this.rules_formDataDetail.formDataDetail.length!=0){
                var count=0
                for (var i=0,length=this.rules_formDataDetail.formDataDetail.length;i<length;i++){
                    this.rules_formDataDetail.formDataDetail[i].sort=i+1
                    var j=count
                    count=j+this.rules_formDataDetail.formDataDetail[i].weightValue
                }
                if (count==100) {
                    this.$refs['formData'].validate((valid1) => {
                        if (valid1) {
                            this.$refs['rules_formDataDetail'].validate((valid) => {
                                if (valid) {
                                    if (this.isEdit){
                                        editObj(Object.assign(this.formData,
                                            {assessTemplateDetails: this.rules_formDataDetail.formDataDetail})).then(response => {
                                            if (response.data.code == 0) {
                                                this.$alert("保存成功");
                                                this.dialogVisible = false
                                                this.getListData()
                                            } else {
                                                this.$alert("提交失败");
                                            }
                                        })
                                    } else {
                                        addObj(Object.assign(this.formData,
                                            {assessTemplateDetails: this.rules_formDataDetail.formDataDetail})).then(response => {
                                            if (response.data.code == 0) {
                                                this.$alert("保存成功");
                                                this.dialogVisible = false
                                                this.getListData()
                                            } else {
                                                this.$alert("提交失败");
                                            }
                                        })
                                    }

                                }
                            })
                        }
                    })
                }else {
                    this.$alert('权重之和必须为100')
                }

            }else{
                this.$alert("至少添加一项考核明细")
            }
        },
        valiTableData(arr){
            let f=false
            for (let i = 0,length=arr.length; i < length-1; i++) {
                for (let j = i+1; j <length; j++) {
                    if(arr[i].item==arr[j].item){
                        f=true;
                        return f;
                    }
                }

            }
            return f;

        },
        deleteDetail(index){
            this.$confirm('您确定要删除该数据吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.rules_formDataDetail.formDataDetail.splice(index, 1)
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        addDetail(){
            let row={
                item:'',
                weightValue:0,
                remarks:'',
            }
            this.rules_formDataDetail.formDataDetail.push(row)
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => {});
        },
        async edit(id){
            this.isEdit=true
            this.dialogVisible=true
            const response = await getObj(id);
            let formData = response.data.data;
            this.formData = formData;
            this.rules_formDataDetail.formDataDetail=formData.assessTemplateDetails
        },
        add(){
            this.isEdit=false
            this.dialogVisible=true
            this.formData={}
            this.rules_formDataDetail.formDataDetail=[]
        },
        del(id){
            this.confirm('删除确认', '您确定要删除该数据吗？', () => {
                delObj(id).then(response=>{
                    if (response.data.code==0){
                        this.suc('删除成功')
                        this.getListData()
                    } else {
                        this.err('删除失败')
                    }
                })
            })


        },
				getListData (params = {}) {
					this.loading = true;
					let requestData = { ...this.params, ...params };
					fetchList(requestData)
						.then(res => {
							const { current, size, total, records } = res.data.data;
							this.tableData = records;
							this.params = requestData;
							this.pager = { total, current, size };
						})
						.finally(() => {
							this.loading = false;
						});
				},
				// 菜单点击监听
				handleMenuClick (type) {
					switch (type) {
						case "add":
							this.add();
							break;
						default:
							this.$message(type);
							break;
					}
				}
    }
}
